<?php

namespace app\service;


use app\model\UserModel;
use app\tool\SingletonTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class UserService
{
    use SingletonTrait;

    /**
     * 通过saas user_id 获取 im  user_id
     * @param int $userId
     * @return array|mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUnionIdByUserId(int $userId)
    {
        $userData = UserModel::where('id', $userId)->field('union_id')->find();
        if (empty($userData)) {
            return [];
        }
        return $userData['union_id'];
    }

    /**
     * 读取更多用户信息
     * @param $unionId
     * @return array|mixed
     */
    public function getOtherUserInfo($unionId)
    {
        $userInfo = teamones_request('teamones-im', 'user/get_other_user_info', ['user_id' => $unionId]);
        if (empty($userInfo['data'])) {
            return [];
        }
        return $userInfo['data'];
    }

    /**
     * 读取用户信息
     * @return array|mixed
     */
    public function getMyUserInfo()
    {
        $userInfo = teamones_request('teamones-im', 'user/get_my_user_info', []);
        if (empty($userInfo['data'])) {
            return [];
        }
        return $userInfo['data'];
    }

    /**
     * 通过im user_id 获取 saas user id
     * @param int $imUserId
     * @return array|mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getSaasUserIdByUnionId(int $imUserId)
    {
        $userData = UserModel::field('id')
            ->where('union_id', $imUserId)
            ->find();
        if (empty($userData->toArray())) {
            return [];
        }
        $data = $userData->toArray();
        return $data['id'];
    }

    /**
     * 通过部门或者角色查询用户
     * @param array $departmentIds
     * @param array $roleCode
     * @param array $tenantId
     * @param array $userId
     * @return array
     */
    public function byDepartmentOrRoleSelectUser(array $departmentIds, array $roleCode, array $tenantId, array $userId): array
    {
        if (empty($departmentIds) && empty($roleCode)) {
            return [];
        }
        $db = (new \app\model\UserModel)->field('user.id as id,user.name as name,user.union_id as union_id')
            ->join('im_user', 'user.union_id = im_user.id')
            ->join('tenant_user', 'user.union_id = tenant_user.user_id')
            ->where('im_user.active', 1);
        if (!empty($departmentIds)) {
            $db
                ->join('tenant_user_department', 'tenant_user_department.tenant_user_id = tenant_user.id')
                ->whereIn('tenant_user_department.department_id', $departmentIds);
        }
        if (!empty($roleCode)) {
            $db
                ->join('tenant_user_role', 'tenant_user_role.tenant_user_id = tenant_user.id')
                ->join('role', 'role.id = tenant_user_role.role_id')
                ->whereIn('role.code', $roleCode);
        }
        if (!empty($tenantId)) {
            $db->whereIn('tenant_user.tenant_id', $tenantId);
        }
        if (!empty($userId)) {
            $db->whereIn('tenant_user.user_id', $userId);
        }
        $userList = $db->group('user.id,user.name,user.union_id')->order('user.id')->select();
        if (empty($userList->toArray())) {
            return [];
        }
        return $userList->toArray();
    }

    /**
     * 获取部门下面用户列表
     * @param array $departmentIds
     * @param int $tenantId
     * @return array
     */
    public function getDepartmentUserMultiDepartmentUser(array $departmentIds, int $tenantId): array
    {
        if (empty($departmentIds)) {
            return [];
        }
        $field = [
            'tenant_user.user_id as union_id',
            'tenant_user_department.department_id as department_id',
            'user.id as user_id',
            'role.name as role_name',
            'user.name as user_name',
            'tenant_user.tenant_id as tenant_id',
            'tenant.name as tenant_name',
        ];
        $departmentUsers = UserModel::field($field)
            ->join('im_user', 'user.union_id = im_user.id')
            ->join('tenant_user', 'user.union_id = tenant_user.user_id')
            ->join('tenant', 'tenant_user.tenant_id = tenant.id')
            ->join('tenant_user_department', 'tenant_user_department.tenant_user_id = tenant_user.id')
            ->join('tenant_user_role', 'tenant_user_role.tenant_user_id = tenant_user.id', 'LEFT')
            ->join('role', 'role.id = tenant_user_role.role_id', 'LEFT')
            ->where('im_user.active', 1)
            ->where('tenant_user.tenant_id', $tenantId)
            ->where('tenant_user.status', 'active')
            ->whereIn('tenant_user_department.department_id', $departmentIds)
            ->select();
        if (empty($departmentUsers->toArray())) {
            return [];
        }
        $departmentUsers = $departmentUsers->toArray();
        $distinctUserIds = [];
        $distinctUserMap = [];
        foreach ($departmentUsers as $user) {
            if (empty($distinctUserMap[$user['user_id']])) {
                $distinctUserMap[$user['user_id']] = $user['user_id'];
                $distinctUserIds[] = $user['user_id'];
            }
        }
        $returnData['department_users'] = $departmentUsers;
        $returnData['distinct_user_ids'] = $distinctUserIds;
        return $returnData;
    }


    /**
     * 通过saas user_id 获取 im user_id
     * @param $saasUserIdList
     * @return array
     */
    public function getUnionIdListByUserIdList($saasUserIdList): array
    {
        if (empty($saasUserIdList)) {
            return [];
        }
        $imUserIdList = (new \app\model\UserModel)->whereIn('id', array_unique($saasUserIdList))->column('union_id');
        if (empty($imUserIdList)) {
            return [];
        }
        return $imUserIdList;
    }

    /**
     * 获取角色部门信息
     * @param $projectId
     * @param $roleCode
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getRoleDepartmentIds($projectId, $roleCode): array
    {
        if (empty($roleCode)) {
            return [];
        }
        $directorRoleId = RoleService::getInstance()->find($roleCode);
        $projectMemberList = (new \app\model\ProjectMemberModel)->field('user_id')
            ->where('project_id', $projectId)
            ->where('role_id', $directorRoleId)
            ->select();
        if (empty($projectMemberList->toArray())) {
            return [];
        }
        $projectMemberUserIdList = [];
        foreach ($projectMemberList->toArray() as $projectMemberItem) {
            $projectMemberUserIdList[] = $projectMemberItem['user_id'];
        }
        return $projectMemberUserIdList;
    }

    /**
     * 获取角色用户ids
     * @param $projectId
     * @param $roleCode
     * @return array
     */
    public function getProjectMemberRoleUserIds($projectId, $roleCode): array
    {
        $userIds = (new \app\model\ProjectMemberModel)->field('user_id')
            ->where('project_id', $projectId)
            ->where('role_code', $roleCode)
            ->column('user_id');
        if (empty($userIds)) {
            return [];
        }
        return array_unique($userIds);
    }

    /**
     * 查询用户列表带分页
     * @param array|string $where
     * @param array $page
     * @return array
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function getUserListPage($where, array $page): array
    {
        $dbr = is_array($where) ? UserModel::where($where) : UserModel::whereRaw($where);
        if (!empty($page) && count($page) > 1) {
            $pageNum = array_shift($page);
            $pageSize = array_shift($page);
            $dbr = $dbr->page($pageNum, $pageSize);
        }
        return $dbr->order('user.id')->select()->toArray();
    }

    /**
     * 获取用户角色信息
     * @param $userId
     * @return array
     */
    public function getUserRoleCodes($userId): array
    {
        if (empty($userId)) {
            return [];
        }
        $userModel = (new \app\model\TenantUsermodel)
            ->join('tenant_user_role', 'tenant_user_role.tenant_user_id = tenant_user.id')
            ->join('role', 'role.id = tenant_user_role.role_id')
            ->field('role.code as code')
            ->where('tenant_user.user_id', $userId)
            ->column('role.code');
        if (empty($userModel)) {
            return [];
        }
        return $userModel;
    }
}

